package com.njupt.towerssystem.services.impl;

import com.google.common.hash.BloomFilter;
import com.njupt.towerssystem.domain.Managers;
import com.njupt.towerssystem.mapper.ManagersMapper;
import com.njupt.towerssystem.services.RegisterManagerService;
import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl;
import javafx.beans.property.Property;
import lombok.Synchronized;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class RegisterManagerServiceImpl implements RegisterManagerService {
    @Resource
    private ManagersMapper managersMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private BloomFilter<String> nameFilter;

    private ReentrantLock lock=new ReentrantLock();
    private static Queue<Integer> userids=new PriorityQueue<>();

    //当springboot工程启动后自动调用本方法对usrids集合填充数据
    @PostConstruct//当程序启动时自动启动本方法一次
    private void addNewUseridToArray(){
        int expect_id=managersMapper.findMaxUserid();
        for(int i=expect_id;i<expect_id+10000;i++){
            userids.add(i);
        }
    }

    //程序启动，将用户名+密码存放到布隆过滤器中的数组中
    @PostConstruct
    private void addManagersToBloom(){
        List<String> names=managersMapper.findAllName();
        for(String name:names){
            nameFilter.put(name);
        }
    }

    @Transactional
    @Override
    public boolean regManager(Managers m) {
        //先去数据库查看用户名是否存在,
        //通过布隆过滤器判断用户名是否存在，不存在则返回false
        boolean nameExist = nameFilter.mightContain(m.getLoginname());
        if(nameExist){
            return false;
        }

        //查询用户注册的预期userid
        Integer expect_id=0;
        lock.lock();
        try {
            if(userids.isEmpty()){
                addNewUseridToArray();
            }
            //从能用userid中拿出一个
            expect_id=userids.poll();
        } finally {
            lock.unlock();
        }
        //先查询期待的userid
//        int expect_id=managersMapper.findMaxUserid();
        //将最大值填充到对象中
        m.setUserid(expect_id);
        //将数据存放到mysql数据库中
        managersMapper.insertManager(m);
        //同时将该数据存放到redis缓存数据库
        stringRedisTemplate.opsForHash().put("managers",
                m.getLoginname()+","+m.getLoginpwd(),m.toString());

        //将当前新建用户的用户名存放到bloom过滤器中
        return true;
    }

}
